<!-- 公务号码与分类管理 -->
<template>
  <PageWrapper dense fixedHeight contentClass="flex">
    <!-- <PageWrapper dense contentFullHeight fixedHeight contentClass="flex"> -->
    <!-- 左侧分类树 -->
    <div class="m-4 mr-0 w-1/4 xl:w-1/5 overflow-hidden bg-white">
      <a-button
        type="success"
        size="small"
        style="margin-left: 2px; margin-right: 2px"
        @click="onAddCategory"
      >
        <plus-outlined />新增
      </a-button>
      <a-button type="primary" size="small" style="margin-right: 2px" @click="onEditCategory">
        <edit-outlined />编辑
      </a-button>
      <a-button type="error" size="small" style="margin-right: 5px" @click="onDeleteCategory">
        <delete-outlined />删除
      </a-button>
      <a-tree
        @select="handleSelect"
        treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
        :defaultExpandAll="true"
        :treeData="treeData.child"
        :fieldNames="fieldNames"
      />
    </div>
    <!-- 右侧公务号码列表 -->
    <BasicTable
      @register="registerTable"
      class="m-0 mr-0 w-3/4 xl:w-4/5 overflow-hidden"
      size="small"
      :searchInfo="searchInfo"
    >
      <!-- 状态标记 -->
      <template #statusFlag="{ record }">
        <template v-if="record.flag == 0">
          <Tag :color="'green'">启用</Tag>
        </template>
        <template v-if="record.flag == 5">
          <Tag :color="'yellow'">禁用</Tag>
        </template>
        <template v-if="record.flag == 9">
          <Tag :color="'red'">已删除</Tag>
        </template>
      </template>

      <template #toolbar>
        <a-button type="success" @click="onAddPhone">新增号码</a-button>
        <a-button type="primary" @click="setCategoryForIds">设置分类</a-button>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <TableAction
            :actions="[
              {
                icon: 'clarity:note-edit-line',
                tooltip: '编辑',
                onClick: onEditPhone.bind(null, record),
              },
              {
                icon: 'ant-design:delete-outlined',
                color: 'error',
                tooltip: '删除',
                popConfirm: {
                  title: '是否确认删除',
                  placement: 'left',
                  confirm: onDeletePhone.bind(null, record),
                },
              },
            ]"
          />
        </template>
      </template>
    </BasicTable>

    <addOrEditCategory @register="registerAddOrEditCategoryForm" @success="opCategorySuccess" />
    <addOrEditPhone @register="registerAddOrEditPhoneForm" @success="opPhoneSuccess" />
    <setCategoryForPhones @register="registerSetCategoryForm" @success="opPhoneSuccess" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, provide, ref } from 'vue';
  import { PageWrapper } from '/@/components/Page';
  import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { Tag } from 'ant-design-vue';
  import { OperationTypeEnum } from '/@/enums/appEnum';

  import { getAll, deleteCategoryById } from '/@/api/addressbook/official/category';
  import { query, deleteById } from '/@/api/addressbook/official/phone';

  import { phoneTableColumns, phoneQueryConditionFormSchema } from './officialphone.data';

  import addOrEditCategory from './AddOrEditCategory.vue';
  import addOrEditPhone from './AddOrEditPhone.vue';
  import setCategoryForPhones from './SetCategoryForPhones.vue';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';

  const { createMessage } = useMessage();
  const [registerAddOrEditCategoryForm, { openModal: openAddOrEditCategoryForm }] = useModal();
  const [registerAddOrEditPhoneForm, { openModal: openAddOrEditPhoneForm }] = useModal();
  const [registerSetCategoryForm, { openModal: openSetCategoryForm }] = useModal();

  export default defineComponent({
    name: 'OfficialManagement',
    components: {
      PageWrapper,
      PlusOutlined,
      EditOutlined,
      DeleteOutlined,
      BasicTable,
      Tag,
      TableAction,
      addOrEditCategory,
      addOrEditPhone,
      setCategoryForPhones,
    },

    setup() {
      //定义模块的名称，提供给子孙组件获取使用
      const categoryModuleName = ref('分类管理');
      provide('categoryModuleName', categoryModuleName);
      const moduleName = ref('公务号码管理');
      provide('moduleName', moduleName);

      const fieldNames = reactive({ children: 'children', title: 'name', key: 'id' });

      const treeData = reactive({
        child: [
          {
            name: '公务号码分类树',
            id: '',
            children: [],
          },
        ],
      });

      //点击分类获取的分类id用于查询公务号码，或者修改或删除分类的条件
      const searchInfo = reactive<Recordable>({});

      /**
       * 点击分类获取分类id
       */
      function handleSelect(keys) {
        // console.log(keys[0]);
        searchInfo.categoryId = keys[0];
        console.log('选中的分类id', searchInfo.categoryId);
        reload();
      }

      /**
       * 获取公务号码分类信息
       */
      getAllCategory();
      function getAllCategory() {
        getAll().then((res) => {
          console.log(res);
          res.push({ id: 0, name: '未分类号码' });
          treeData.child[0].children = res;
        });
      }

      /**
       * 获取公务号码信息
       */
      const [registerTable, { reload, getSelectRowKeys, clearSelectedRowKeys }] = useTable({
        title: '公务号码管理',
        api: query,
        columns: phoneTableColumns,
        useSearchForm: true,
        formConfig: {
          labelWidth: 80,
          schemas: phoneQueryConditionFormSchema,
          autoSubmitOnEnter: true,
        },
        // scroll: { y: 300 },
        showTableSetting: true,
        bordered: true,
        striped: false,
        canResize: true,
        actionColumn: {
          width: 120,
          title: '操作',
          dataIndex: 'action',
          fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
        rowSelection: { type: 'checkbox' },
        rowKey: 'id',
        clickToRowSelect: false, //开启点击行选中/取消checkbox
      });

      /**
       * 打开新增分类窗口
       */
      function onAddCategory() {
        openAddOrEditCategoryForm(true, { op: OperationTypeEnum.ADD });
      }

      /**
       * 打开编辑分类窗口
       */
      function onEditCategory() {
        if (searchInfo.categoryId != undefined && searchInfo.categoryId != null) {
          openAddOrEditCategoryForm(true, {
            op: OperationTypeEnum.EDIT,
            categoryId: searchInfo.categoryId,
          });
        } else {
          createMessage.warning('请选中要编辑的分类', 2);
        }
      }

      /**
       * 删除分类
       */
      function onDeleteCategory() {
        if (searchInfo.categoryId != undefined && searchInfo.categoryId != null) {
          deleteCategoryById(searchInfo.categoryId)
            .then((res) => {
              console.log('res', res);
              //res判断结果：同时==undefined和null
              if (res == undefined && (res == null || Object.keys(res).length == 0)) {
                createMessage.success('删除分类成功。', 2);
                opCategorySuccess();
              }
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } else {
          createMessage.warning('请选中要删除的分类', 2);
        }
      }

      /**
       * 打开新增号码窗口
       */
      function onAddPhone() {
        openAddOrEditPhoneForm(true, {
          op: OperationTypeEnum.ADD,
          categoryId: searchInfo.categoryId,
        });
      }

      /**
       * 给选中的号码设置所属分类
       */
      function setCategoryForIds() {
        if (getSelectRowKeys().length == 0) {
          createMessage.warning('请勾选号码');
        } else {
          // console.log('选中的号码', getSelectRowKeys());
          openSetCategoryForm(true, { op: '设置分类', phoneIds: getSelectRowKeys() });
        }
      }

      /**
       * 打开编辑号码窗口
       */
      function onEditPhone(record: Recordable) {
        openAddOrEditPhoneForm(true, { op: OperationTypeEnum.EDIT, dataId: record.id });
      }

      /**
       * 删除号码
       */
      function onDeletePhone(record: Recordable) {
        deleteById(record.id)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              opPhoneSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 分类操作成功后的操作
       */
      function opCategorySuccess() {
        getAllCategory();
      }

      /**
       * 号码操作成功后的操作
       */
      function opPhoneSuccess() {
        reload();
        clearSelectedRowKeys();
      }

      return {
        categoryModuleName,
        moduleName,
        handleSelect,
        fieldNames,
        treeData,
        searchInfo,

        getAllCategory,
        registerAddOrEditCategoryForm,
        onAddCategory,
        onEditCategory,
        onDeleteCategory,

        registerTable,
        opCategorySuccess,
        opPhoneSuccess,
        registerAddOrEditPhoneForm,
        onAddPhone,
        onEditPhone,
        onDeletePhone,
        setCategoryForIds,
        registerSetCategoryForm,
      };
    },
  });
</script>
